<template>
  <div class="map">
    <el-select v-model="formData.province" value-key="id" filterable remote reserve-keyword remote-show-suffix>
      <el-option v-for="item in regions" :key="item.id" :label="item.name" :value="item" />
    </el-select>
    <el-select v-model="formData.city" value-key="id" filterable remote reserve-keyword remote-show-suffix>
      <el-option v-for="item in formData.province?.children" :key="item.id" :label="item.name" :value="item" />
    </el-select>
    <el-select v-model="formData.district" value-key="id" filterable remote reserve-keyword remote-show-suffix>
      <el-option v-for="item in formData.city?.children" :key="item.id" :label="item.name" :value="item" />
    </el-select>
    <el-input class="map-input" v-model="formData.address">
      <template #append>
        <el-button @click="location">
          <el-icon><Location /></el-icon>
        </el-button>
      </template>
    </el-input>
  </div>
  <div id="Amap-container" :style="props.style"></div>
</template>
<script lang="ts" setup name="Amap">
import { ref, reactive, shallowRef, watch } from "vue";
import region from "./region.json";
import { AMAP_MAP_KEY } from "@/config/index";
import AMapLoader from "@amap/amap-jsapi-loader";

const props = defineProps({
  style: {
    type: String,
    default: "width:100%;height:400px;"
  },
  modelValue: {
    type: [Object, String]
  }
});

const formData = reactive({
  province: props.modelValue.province,
  city: props.modelValue.city,
  district: props.modelValue.district,
  address: props.modelValue.address,
  lat: props.modelValue.lat,
  lng: props.modelValue.lng
});

watch(
  () => props.modelValue,
  newValue => {
    console.log(newValue);
  }
);
const setFormDataLatLng = (lng, lat) => {
  formData.lat = lat;
  formData.lng = lng;
};

//监听 formData 的变化
const onFormDataChange = AMap => {
  watch(
    () => formData.province,
    newValue => {
      if (isReset.value) return;
      formData.city = newValue.children[0];
    }
  );
  watch(
    () => formData.city,
    newValue => {
      if (isReset.value) return;
      formData.district = newValue.children[0];
    }
  );
  watch(
    () => formData.district,
    newValue => {
      if (isReset.value) return;
      formData.address = "";
      AMap.setCenter(newValue.center);
    }
  );
};

const regions = ref(region[0].children);
const isReset = ref(false);
const initFormDataByCenter = adcode => {
  if (!adcode || formData.district.adcode == adcode) return;
  isReset.value = true;
  regions.value.forEach(province => {
    province.not = true;
    province.children?.forEach(city => {
      city.not = true;
      city.children?.forEach(district => {
        district.not = true;
        if (district.adcode == adcode) {
          formData.province = province;
          formData.city = city;
          formData.district = district;
          return;
        }
      });
    });
  });

  setTimeout(() => {
    isReset.value = false;
  }, 200);
};

const AMapClass = () => {
  const map = shallowRef(null);
  const marker = ref();
  const that = reactive({});

  const loadAMap = AMap => {
    const config = {
      viewMode: "3D", //是否为3D地图模式 3D 2D
      zoom: 15, //初始化地图级别 2-30
      pitch: 40, //地图俯仰角度，有效范围 0 度- 83 度
      terrain: true // 开启地形图
    };

    if (formData.lat && formData.lng) {
      config.center = [formData.lng, formData.lat];
    } else if (formData.district) {
      config.center = formData.district.center.split(",");
    } else if (formData.city) {
      config.center = formData.city.center.split(",");
    } else if (formData.province) {
      config.center = formData.province.center.split(",");
    }

    map.value = new AMap.Map("Amap-container", config);
    map.value.on("click", e => {
      setCenter(e.lnglat);
      lnglatToAddress(that.AMap, true);
    });
  };

  const loadToolBar = AMap => {
    // 在图面添加工具条控件, 工具条控件只有缩放功能
    AMap.plugin(["AMap.ToolBar"], function () {
      map.value.addControl(new AMap.ToolBar());
    });
  };
  // 监听经纬度设置
  const setCenter = position => {
    if (!marker.value) return;
    if (typeof position == "string") {
      position = position.split(",");
      setFormDataLatLng(position[0], position[1]);
    } else {
      setFormDataLatLng(position.lng, position.lat);
    }

    map.value.setCenter(position);
    marker.value.setPosition(position);
  };

  //监听地图移动经纬度的变更
  const loadCenter = AMap => {
    //获取地图中心点位置
    const latLng = map.value.getCenter();
    const position = [latLng.lng, latLng.lat];
    if (marker.value) {
      marker.value.setPosition(position);
    } else {
      marker.value = new AMap.Marker({
        icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
        position: position,
        zooms: 20,
        offset: new AMap.Pixel(-27, -53)
      });

      marker.value.setMap(map.value);
      map.value.on("dragging", loadCenter);
    }

    setFormDataLatLng(position[0], position[1]);
    lnglatToAddress(that.AMap, true, position[0], position[1]);
  };

  let timeoutId = null;
  const lnglatToAddress = (AMap, isCenter, lng, lat) => {
    AMap.plugin("AMap.Geocoder", function () {
      const geocoder = new AMap.Geocoder({
        city: "010" // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
      });

      if (timeoutId) clearTimeout(timeoutId);

      timeoutId = setTimeout(() => {
        if (lng === undefined || lat === undefined) {
          let center = map.value.getCenter();
          lng = center.lng;
          lat = center.lat;
        } else if (lng && lat === undefined) {
          let center = lng.split(",");
          lng = center[0];
          lat = center[1];
        }

        const lnglat = [lng, lat];
        geocoder.getAddress(lnglat, function (status, result) {
          if (status === "complete" && result.info === "OK") {
            formData.address = result.regeocode.formattedAddress.replace(
              result.regeocode.addressComponent.province +
                result.regeocode.addressComponent.city +
                result.regeocode.addressComponent.district,
              ""
            );
            if (isCenter) initFormDataByCenter(result.regeocode.addressComponent.adcode);
          }
        });
      }, 400);
    });
  };

  const init = async () => {
    await AMapLoader.load({
      key: AMAP_MAP_KEY, // 申请好的Web端开发者Key，首次调用 load 时必填
      version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins: ["CitySearch", "ToolBar"] // 需要使用的的插件列表，如比例尺'AMap.Scale'等
    }).then(AMap => {
      that.AMap = AMap;
      loadAMap(AMap);
      loadToolBar(AMap);
      loadCenter(AMap);
    });
  };

  init();
  return {
    setCenter: setCenter,
    lnglatToAddress: (lng, lat) => {
      lnglatToAddress(that.AMap, true, lng, lat);
    }
  };
};
const AMap = AMapClass();
onFormDataChange(AMap);
const location = () => {
  AMap.lnglatToAddress();
};

const emits = defineEmits(["change"]);
watch(formData, newValue => {
  emits("change", newValue);
});
</script>
<style scoped>
.map {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  grid-gap: 10px;
  width: 100%;
  padding: 0 2px;
  margin-bottom: 5px;
}
.map-input {
  grid-column: span 2;
}
#Amap-container {
  width: 100%;
  min-height: 400px;
}
</style>
